//
//  SettingViewController.swift
//  TimMusic
//
//  Created by nkl on 2024/10/11.
//

import Foundation
import UIKit
import StoreKit
let httpAppStoreLink = "https://apps.apple.com/app/id6737406406"

class SettingViewController: BasicBGViewController, UITableViewDelegate {
    lazy var topView: TopBarView = TopBarView(imgName: "ic_setting_top", types: [])
    var viewModel: SettingViewModel = .init()

    lazy var listView: UITableView = {
        let list = UITableView()
        list.delegate = self
        list.dataSource = self.viewModel
        list.register(cell: SettingViewCell<SettingModel>.self)
        list.backgroundColor = .clear
        list.separatorStyle = .none
        return list
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel.requestDatas()
    }

    override func addChildren() {
        super.addChildren()
        view.addSubview(topView)
        view.addSubview(listView)
    }

    override func makeConstraints() {
        super.makeConstraints()
        topView.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(44)
        }

        listView.snp.makeConstraints { make in
            make.top.equalTo(topView.snp.bottom).offset(16)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-tabbarHeight)
        }
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 74
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row >= viewModel.datas.count {
            return
        }
        let cellVModel = viewModel.datas[indexPath.row]
        switch cellVModel.cellModel.type {
        case .privacy:
            if let url = URL.init(string: "https://doc-hosting.flycricket.io/musicnow-privacy-policy/e6b808cb-f3a2-450d-abd6-f88714a9da76/privacy") {
                let webVc = TMWebViewController()
                webVc.loadData(url: url)
                navigationController?.pushViewController(webVc, animated: true)
            }

        case .agement:
            if let url = URL.init(string: "https://doc-hosting.flycricket.io/musicnow-terms-of-use/d34f2246-0229-4e33-b1e4-71be94561958/terms") {
                let webVc = TMWebViewController()
                webVc.loadData(url: url)
                navigationController?.pushViewController(webVc, animated: true)
            }
            break
        case .about:
            break
        case .share:
            shareApp()
            break
        case .update:
            updateApp()
            break
        case .rate:
            rateAction()
            break
        }
    }
    
    func updateApp(){
        guard let appStoreURL = URL(string: httpAppStoreLink) else { return }

        if UIApplication.shared.canOpenURL(appStoreURL) {
            UIApplication.shared.open(appStoreURL, options: [:], completionHandler: nil)
        }
    }
    //6737406406
    func shareApp() {
        let text = "MusicNow - Widgets & Standby".localized()
        let url = URL(string: httpAppStoreLink)!
        let image = UIImage.init(named: "small_logo_ic")!.compressImageSize(to: CGSize(width: 100, height: 100))
        let final = ShareActivityItemProvider(placeholderItem: image)
        let vc = UIActivityViewController(activityItems: [url, final, text], applicationActivities: nil)
        vc.completionWithItemsHandler = { activity, _, _, _ in
            if let type = activity, type == .copyToPasteboard {
                UIPasteboard.general.string = httpAppStoreLink
            }
        }

        TMTabbarViewController.rootTabbar?.present(vc, animated: true)
    }
    
    func rateAction() {
        let countKey = "ProcessCompletedCountKey"
        // If the app doesn't store the count, this returns 0.
        var count = UserDefaults.standard.integer(forKey: countKey)
        count += 1
        UserDefaults.standard.set(count, forKey: countKey)
        /// 如果当前版本 弹过一次 那么下一次就走url
        /// 如果当前版本 没弹过，那就弹
        if count >= 4 {
            let openStr = "itms-apps://itunes.apple.com/app/id6737406406?action=write-review"
            if let url = URL(string: openStr), UIApplication.shared.canOpenURL(url) {
                if #available(iOS 10.0, *) {
                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                } else {
                    UIApplication.shared.canOpenURL(url)
                }
            } else {
                print("链接出错")
            }
        } else {
            SKStoreReviewController.requestReview()
        }
    }

}



class ShareActivityItemProvider: UIActivityItemProvider {
    // 解决AirDrop分享app失败的问题
    override func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
        if activityType == .airDrop {
            return nil
        }
        return placeholderItem
    }
}
